package gwu.android;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 * The first activity of the ReaderApp.  Opens to a main page with a list of available articles. 
 * Contains code for the options menu that allows the user to add a new article to the database 
 * as well as code for a context menu that allows a user to delete an article. 
 * @author Taylor Sandelius
 *
 */
public class ReaderApp extends ListActivity {
    private static final int ACTIVITY_CREATE=0;
    private static final int ACTIVITY_READ=1;

    //ID is the article ID
    private static final int INSERT_ID = Menu.FIRST;
    private static final int DELETE_ID = Menu.FIRST + 1;
    private static final int READ_ID = Menu.FIRST + 2; 
    private static final int SCORE_ID = Menu.FIRST + 3;
    private ArticleDbAdapter mDbHelper;
    private WordItemsDbAdapter mDbHelper2;
    private Cursor mArticleCursor;
    private Cursor mWordItemsCursor;

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.main);
      setTitle("The Reader App!");
      mDbHelper = new ArticleDbAdapter(this);
      mDbHelper2 = new WordItemsDbAdapter(this);
      mDbHelper.open();
      mDbHelper2.open();
      fillData();
      registerForContextMenu(getListView());
  }

  private void fillData() {
      // Get all of the rows from the database and create the item list
      mArticleCursor = mDbHelper.fetchAllArticles();
      startManagingCursor(mArticleCursor);

      // Create an array to specify the fields we want to display in the list (only TITLE)
      String[] from = new String[]{ArticleDbAdapter.KEY_TITLE};

      // and an array of the fields we want to bind those fields to (in this case just text1)
      int[] to = new int[]{R.id.text1};

      // Now create a simple cursor adapter and set it to display
      SimpleCursorAdapter notes = 
          new SimpleCursorAdapter(this, R.layout.articles_row, mArticleCursor, from, to);
      setListAdapter(notes);
  }
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
      super.onCreateOptionsMenu(menu);
      menu.add(0, INSERT_ID, 0, R.string.menu_insert);
      //menu.add(0, TOTAL_ID, 0, R.string.menu_totalScore);
      return true;
  }

  /**
   * This method is for menu options when the user selects the menu button
   */
  @Override
  public boolean onMenuItemSelected(int featureId, MenuItem item) {
      switch(item.getItemId()) {
          case INSERT_ID:
              addArticle();
              return true;
      }
      return super.onMenuItemSelected(featureId, item);
  }

  /**
   * This method is for declaring context menu options (responds to a long touch on list item)
   */
  @Override
  public void onCreateContextMenu(ContextMenu menu, View v,
          ContextMenuInfo menuInfo) {
      super.onCreateContextMenu(menu, v, menuInfo);
      menu.add(0, DELETE_ID, 0, R.string.menu_delete);
      menu.add(0, SCORE_ID, 0, R.string.menu_articleScore);
  }

  @Override
  public boolean onContextItemSelected(MenuItem item) {
      switch(item.getItemId()) {
          case DELETE_ID:
              AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
              mDbHelper.deleteArticle(info.id);
              mDbHelper2.deleteArticleWords(info.id);
              fillData();
              return true;
          case SCORE_ID:
              AdapterContextMenuInfo info2 = (AdapterContextMenuInfo) item.getMenuInfo();
              Cursor c2 = mWordItemsCursor;
              c2 = mDbHelper2.fetchArticle(info2.id);
              ArrayList<Integer> wordScores = mDbHelper2.scoreArticle(c2);
              Intent i = new Intent(this, DisplayArticleScores.class);
              i.putExtra(WordItemsDbAdapter.KEY_SCORE, wordScores);
              startActivity(i);
              return true;
      }
      return super.onContextItemSelected(item);
  }
  
  private void addArticle() {
      Intent i = new Intent(this, CreateArticle.class);
      startActivityForResult(i, ACTIVITY_CREATE);
  }
  
  @Override
  protected void onListItemClick(ListView l, View v, int position, long id) {
      super.onListItemClick(l, v, position, id);
      Cursor c = mArticleCursor;
      Cursor c2 = mWordItemsCursor;
      c2 = mDbHelper2.fetchArticle(id);
      c.moveToPosition(position);
      Intent i = new Intent(this, ReadArticle.class);
      
      //Put the row id (used to connect the article to its word items in the WordItem table),
      //the article title, and the article text body on the intent passed to ReadArticle
      i.putExtra(ArticleDbAdapter.KEY_ROWID, id);
      i.putExtra(ArticleDbAdapter.KEY_TITLE, c.getString(
              c.getColumnIndexOrThrow(ArticleDbAdapter.KEY_TITLE)));
      i.putExtra(ArticleDbAdapter.KEY_BODY, c.getString(
              c.getColumnIndexOrThrow(ArticleDbAdapter.KEY_BODY)));
      
      //Retrieve the array lists of the word IDs and their answers and foils
      ArrayList<Integer> wordIds = new ArrayList<Integer>();
      ArrayList<String> answers = new ArrayList<String>();
      ArrayList<String> foils1 = new ArrayList<String>();
      ArrayList<String> foils2 = new ArrayList<String>();
      ArrayList<String> foils3 = new ArrayList<String>();
      ArrayList<Integer> scores = mDbHelper2.scoreArticle(c2);
      c2.moveToFirst();
      for(int j=0; j<c2.getCount(); j++){
    	  wordIds.add(c2.getInt(c2.getColumnIndexOrThrow(WordItemsDbAdapter.KEY_WORDID)));
    	  answers.add(c2.getString(c2.getColumnIndexOrThrow(WordItemsDbAdapter.KEY_ANSWER)));
    	  foils1.add(c2.getString(c2.getColumnIndexOrThrow(WordItemsDbAdapter.KEY_FOIL1)));
    	  foils2.add(c2.getString(c2.getColumnIndexOrThrow(WordItemsDbAdapter.KEY_FOIL2)));
    	  foils3.add(c2.getString(c2.getColumnIndexOrThrow(WordItemsDbAdapter.KEY_FOIL3)));    	  
    	  c2.moveToNext();
      }
      
      //Put the array lists on the intent
      i.putIntegerArrayListExtra(WordItemsDbAdapter.KEY_WORDID, wordIds);
      i.putStringArrayListExtra(WordItemsDbAdapter.KEY_ANSWER, answers);
      i.putStringArrayListExtra(WordItemsDbAdapter.KEY_FOIL1, foils1);
      i.putStringArrayListExtra(WordItemsDbAdapter.KEY_FOIL2, foils2);
      i.putStringArrayListExtra(WordItemsDbAdapter.KEY_FOIL3, foils3);
      i.putIntegerArrayListExtra(WordItemsDbAdapter.KEY_SCORE, scores);

      c.close();
      c2.close();
      startActivityForResult(i, ACTIVITY_READ);
  }
  
  
  @Override
  protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
      super.onActivityResult(requestCode, resultCode, intent);
      if(resultCode != Activity.RESULT_CANCELED){
	      Bundle extras = intent.getExtras();
	      switch(requestCode) {
	          case ACTIVITY_CREATE:
	              String title = extras.getString(ArticleDbAdapter.KEY_TITLE);
	              String body = extras.getString(ArticleDbAdapter.KEY_BODY);
	              ArrayList<Integer> wordIDs = extras.getIntegerArrayList(WordItemsDbAdapter.KEY_WORDID);
	              ArrayList<String> answers = extras.getStringArrayList(WordItemsDbAdapter.KEY_ANSWER);
	              ArrayList<String> foils1 = extras.getStringArrayList(WordItemsDbAdapter.KEY_FOIL1);
	              ArrayList<String> foils2 = extras.getStringArrayList(WordItemsDbAdapter.KEY_FOIL2);
	              ArrayList<String> foils3 = extras.getStringArrayList(WordItemsDbAdapter.KEY_FOIL3);
	
	              Long articleId = mDbHelper.createArticle(title, body);
	              //Add a row to WordItems table for each word ID with its article id,
	              //answer and foils
	              for(int i = 0; i<wordIDs.size(); i++){
	            	  mDbHelper2.createWordItem(articleId, wordIDs.get(i), answers.get(i),
	            			  foils1.get(i),foils2.get(i),foils3.get(i), 0);
	              }

	              break;
	              
	          case ACTIVITY_READ:
	        	  ArrayList<Integer> updatedScores = extras.getIntegerArrayList(WordItemsDbAdapter.KEY_SCORE);
	        	  long artId = extras.getLong(WordItemsDbAdapter.KEY_ARTICLEID);
	        	  ArrayList<Integer> wordIds = extras.getIntegerArrayList(WordItemsDbAdapter.KEY_WORDID);
	        	  for(int i = 0; i < wordIds.size(); i++){
	        		  mDbHelper2.updateScore(artId, wordIds.get(i)+"", updatedScores.get(i));
	        	  }
	        	  fillData();
	              break;
	      }
      }
      //The activity crashed or the user selected the back button
      else fillData();
      
  }
  

}